<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="操作人" prop="operator">
        <el-input v-model="searchForm.operator" placeholder="请输入操作人" clearable />
      </el-form-item>
      <el-form-item label="操作模块" prop="module">
        <el-select v-model="searchForm.module" placeholder="请选择操作模块" clearable style="width: 180px">
          <el-option label="用户管理" value="USER" />
          <el-option label="角色管理" value="ROLE" />
          <el-option label="生产管理" value="PRODUCTION" />
          <el-option label="质量管理" value="QUALITY" />
          <el-option label="设备管理" value="EQUIPMENT" />
          <el-option label="库存管理" value="INVENTORY" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型" prop="operationType">
        <el-select v-model="searchForm.operationType" placeholder="请选择操作类型" clearable style="width: 180px">
          <el-option label="新增" value="CREATE" />
          <el-option label="修改" value="UPDATE" />
          <el-option label="删除" value="DELETE" />
          <el-option label="查询" value="SELECT" />
          <el-option label="登录" value="LOGIN" />
          <el-option label="登出" value="LOGOUT" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择操作状态" clearable style="width: 180px">
          <el-option label="成功" value="SUCCESS" />
          <el-option label="失败" value="FAILURE" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="dateRange">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="success" :icon="Download" @click="handleExport">导出日志</el-button>
      <el-button type="danger" :icon="Delete" @click="handleClear">清空日志</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="operator" label="操作人" />
      <el-table-column prop="module" label="操作模块">
        <template #default="scope">
          <el-tag :type="getModuleTag(scope.row.module)">{{ getModuleText(scope.row.module) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operationType" label="操作类型">
        <template #default="scope">
          <el-tag :type="getOperationTypeTag(scope.row.operationType)">{{ getOperationTypeText(scope.row.operationType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operationDesc" label="操作描述" show-overflow-tooltip />
      <el-table-column prop="requestMethod" label="请求方式">
        <template #default="scope">
          <el-tag :type="getMethodTag(scope.row.requestMethod)" size="small">{{ scope.row.requestMethod }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="requestUrl" label="请求地址" show-overflow-tooltip />
      <el-table-column prop="ipAddress" label="IP地址" />
      <el-table-column prop="userAgent" label="用户代理" show-overflow-tooltip />
      <el-table-column prop="status" label="操作状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="executeTime" label="执行时间(ms)" align="right">
        <template #default="scope">
          <span :class="getExecuteTimeClass(scope.row.executeTime)">{{ scope.row.executeTime }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="operationTime" label="操作时间" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleView(scope.row)">查看详情</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<script setup lang="ts" name="operationLog">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Download, Delete } from "@element-plus/icons-vue";

const loading = ref(false);
const tableData = ref([]);
const searchFormRef = ref<FormInstance>();

// 查询表单
const searchForm = reactive({
  operator: "",
  module: "",
  operationType: "",
  status: "",
  dateRange: []
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取模块标签
const getModuleTag = (module: string) => {
  const moduleMap: Record<string, string> = {
    USER: "primary",
    ROLE: "success",
    PRODUCTION: "warning",
    QUALITY: "danger",
    EQUIPMENT: "info",
    INVENTORY: "primary"
  };
  return moduleMap[module] || "info";
};

// 获取模块文本
const getModuleText = (module: string) => {
  const moduleMap: Record<string, string> = {
    USER: "用户管理",
    ROLE: "角色管理",
    PRODUCTION: "生产管理",
    QUALITY: "质量管理",
    EQUIPMENT: "设备管理",
    INVENTORY: "库存管理"
  };
  return moduleMap[module] || module;
};

// 获取操作类型标签
const getOperationTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    CREATE: "success",
    UPDATE: "warning",
    DELETE: "danger",
    SELECT: "info",
    LOGIN: "primary",
    LOGOUT: "info"
  };
  return typeMap[type] || "info";
};

// 获取操作类型文本
const getOperationTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    CREATE: "新增",
    UPDATE: "修改",
    DELETE: "删除",
    SELECT: "查询",
    LOGIN: "登录",
    LOGOUT: "登出"
  };
  return typeMap[type] || type;
};

// 获取请求方式标签
const getMethodTag = (method: string) => {
  const methodMap: Record<string, string> = {
    GET: "success",
    POST: "primary",
    PUT: "warning",
    DELETE: "danger"
  };
  return methodMap[method] || "info";
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    SUCCESS: "success",
    FAILURE: "danger"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    SUCCESS: "成功",
    FAILURE: "失败"
  };
  return statusMap[status] || status;
};

// 获取执行时间样式
const getExecuteTimeClass = (time: number) => {
  if (time > 3000) return "execute-time-slow";
  if (time > 1000) return "execute-time-normal";
  return "execute-time-fast";
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: 1,
        operator: "admin",
        module: "USER",
        operationType: "CREATE",
        operationDesc: "新增用户：张三",
        requestMethod: "POST",
        requestUrl: "/api/user/create",
        ipAddress: "192.168.1.100",
        userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        status: "SUCCESS",
        executeTime: 156,
        operationTime: "2024-01-15 10:30:00"
      },
      {
        id: 2,
        operator: "zhangsan",
        module: "PRODUCTION",
        operationType: "UPDATE",
        operationDesc: "修改工单状态：WO202401150001",
        requestMethod: "PUT",
        requestUrl: "/api/workorder/update",
        ipAddress: "192.168.1.101",
        userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        status: "SUCCESS",
        executeTime: 89,
        operationTime: "2024-01-15 14:15:00"
      },
      {
        id: 3,
        operator: "lisi",
        module: "QUALITY",
        operationType: "DELETE",
        operationDesc: "删除质检记录：QC202401150001",
        requestMethod: "DELETE",
        requestUrl: "/api/quality/delete",
        ipAddress: "192.168.1.102",
        userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        status: "FAILURE",
        executeTime: 2156,
        operationTime: "2024-01-15 16:45:00"
      },
      {
        id: 4,
        operator: "wangwu",
        module: "EQUIPMENT",
        operationType: "SELECT",
        operationDesc: "查询设备列表",
        requestMethod: "GET",
        requestUrl: "/api/equipment/list",
        ipAddress: "192.168.1.103",
        userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        status: "SUCCESS",
        executeTime: 45,
        operationTime: "2024-01-15 17:20:00"
      },
      {
        id: 5,
        operator: "admin",
        module: "USER",
        operationType: "LOGIN",
        operationDesc: "用户登录系统",
        requestMethod: "POST",
        requestUrl: "/api/auth/login",
        ipAddress: "192.168.1.100",
        userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        status: "SUCCESS",
        executeTime: 234,
        operationTime: "2024-01-15 08:30:00"
      }
    ];
    
    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error("获取操作日志失败:", error);
    ElMessage.error("获取操作日志失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 导出日志
const handleExport = () => {
  ElMessage.info("导出操作日志功能开发中");
};

// 清空日志
const handleClear = () => {
  ElMessageBox.confirm("确认清空所有操作日志吗？此操作不可恢复！", "清空日志确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        ElMessage.success("操作日志清空成功");
        getTableData();
      } catch (error) {
        console.error("操作日志清空失败:", error);
        ElMessage.error("操作日志清空失败");
      }
    })
    .catch(() => {
      // 取消清空
    });
};

// 查看详情
const handleView = (row: any) => {
  ElMessage.info(`查看操作日志 ${row.id} 详情`);
};

// 删除日志
const handleDelete = async (row: any) => {
  ElMessageBox.confirm(`确认删除该条操作日志吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        ElMessage.success("操作日志删除成功");
        getTableData();
      } catch (error) {
        console.error("操作日志删除失败:", error);
        ElMessage.error("操作日志删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

.execute-time-fast {
  color: #67c23a;
  font-weight: bold;
}

.execute-time-normal {
  color: #e6a23c;
  font-weight: bold;
}

.execute-time-slow {
  color: #f56c6c;
  font-weight: bold;
}
</style>